<template>
  <div>
    <el-header
      ><el-row class="top-contain-wraper">
        <el-col :span="6">
          <div class="top-contain-left">
            <div class="top-contain-icon">
              <img src="../assets/img/logo.png" alt="" />
            </div>
            <div class="search">
              <el-autocomplete
                prefix-icon="el-icon-search"
                v-model="searchQuery.word"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                :trigger-on-focus="false"
                clearable
                @select="handleSearchSelect"
                :style="{
                  'background-color': '#f0f1f4',
                }"
              ></el-autocomplete>
            </div>
          </div>
        </el-col>
        <el-col :span="12"
          ><div class="top-contain-center">
            <el-menu
              :router="true"
              menu-trigger="click"
              active-text-color="#ff8200"
              :default-active="activeIndex"
              mode="horizontal"
              @select="selectMenuItem"
            >
              <el-menu-item index="/"
                ><i class="icon-shouye iconfont"></i
              ></el-menu-item>
              <el-menu-item index="/hotrank"
                ><i class="icon-resou iconfont"></i
              ></el-menu-item>
              <el-menu-item index="/news"
                ><i class="icon-xinfengtianchong iconfont"></i
              ></el-menu-item>
              <el-menu-item index="/mine"
                ><i class="icon-wodexiao iconfont" v-if="!user_id"></i>
                <el-image
                  v-else
                  class="pic"
                  :src="
                    userUrl(userInfo.avatar)
                      ? userUrl(userInfo.avatar)
                      : defalutAvatar
                  "
                  fit="fill"
                ></el-image>
              </el-menu-item>
            </el-menu></div
        ></el-col>
        <el-col :span="6">
          <div class="top-contain-right">
            <template v-if="!user_id">
              <div class="member-login-register">
                <div
                  type="text"
                  class="member-login"
                  @click="showLoginDialog = !showLoginDialog"
                >
                  登录
                </div>
                <div
                  type="text"
                  class="member-register"
                  @click="showRegisterDialog = !showRegisterDialog"
                >
                  注册
                </div>
              </div>
            </template>
            <template v-else>
              <div class="logout-wrap" @click="logOut">
                <i class="icon-icon iconfont">退出</i>
              </div>
            </template>

            <div class="write-wrap">
              <div class="write" @click="articleDialogShow">
                <i class="el-icon-edit"></i>
              </div>
            </div>
          </div>
        </el-col> </el-row
    ></el-header>

    <!-- 发表文章 -->
    <publishArticle
      :showArticleDialog="showArticleDialog"
      @articleDialogClosed="articleDialogClosed"
    ></publishArticle>
    <!-- 注册用户 -->
    <register
      :showRegisterDialog="showRegisterDialog"
      @registerDialogClosed="registerDialogClosed"
    ></register>
    <!-- 登录用户 -->
    <login
      :showLoginDialog="showLoginDialog"
      @loginDialogClosed="loginDialogClosed"
    ></login>
  </div>
</template>

<script>
import publishArticle from "../components/publisharticle/PublishArticle.vue";
import register from "../components/Register.vue";
import login from "../components/Login.vue";
import { mapState, mapMutations } from "vuex";
import config from "@/config/index";
export default {
  components: {
    publishArticle,
    register,
    login,
  },
  created() {
    //在页面刷新时将vuex里的信息保存到localStorage里
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem("headerIndex", this.activeIndex);
    });
  },
  data() {
    return {
      // 默认头像
      defalutAvatar: config.defalutAvatar,
      // 图片展示失败默认图片
      defalutPic: config.defalutPic,
      // logo图片
      logoPic: config.logoPic,
      activeIndex: sessionStorage.getItem("headerIndex") || "/",
      user: {
        login: false,
      },
      // 是否显示发表文章对话框
      showArticleDialog: false,
      // 是否显示注册用户对话框
      showRegisterDialog: false,
      // 是否显示登录用户对话框
      showLoginDialog: false,
      // 搜索查询参数
      searchQuery: {
        // 搜索输入值
        word: "",
        page: 1,
        limit: 10,
      },
    };
  },
  computed: { ...mapState("m_user", ["user_id", "userInfo"]) },
  methods: {
    // 用户的头像
    userUrl(userUrl) {
      if (!userUrl) return null;
      // 用户的头像加地址前缀
      return config.defalutBaseURLPic + userUrl;
    },
    ...mapMutations("m_user", [
      "SET_USER_ID",
      "SET_accessToken",
      "SET_refreshToken",
      "SET_tokenType",
      "UPDATE_USER_INFO",
    ]),
    selectMenuItem(index, path) {
      console.log(path);
      if (path[0] != "/") {
        if (!localStorage.user_id) {
          this.activeIndex = "/";
          return this.$showMsg({
            msg: "请请先登录!",
            type: "warning",
          });
        }
      }

      if (index == "/news") {
        return this.$showMsg({
          msg: "尚请期待！",
          type: "warning",
        });
      }

      this.activeIndex = index;
    },
    // 写文章对话框的展示事件
    articleDialogShow() {
      if (!localStorage.user_id) {
        return this.$showMsg({
          msg: "请请先登录!",
          type: "warning",
        });
      }
      this.showArticleDialog = !this.showArticleDialog;
    },
    // 注册对话框关闭事件
    registerDialogClosed() {
      this.showRegisterDialog = false;
    },
    // 登录对话框关闭事件
    loginDialogClosed() {
      this.showLoginDialog = false;
    },
    // 写文章对话框关闭事件
    articleDialogClosed() {
      this.showArticleDialog = false;
    },
    // 登出操作
    logOut() {
      this.$confirm("此操作将退出登录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // this.$http.post("/oauth/logout");
          this.SET_USER_ID("-1");
          this.SET_accessToken("-1");
          this.SET_refreshToken("-1");
          this.SET_tokenType("-1");
          this.UPDATE_USER_INFO({});
          // 返回首页
          this.activeIndex = "/";
          if (this.$route.path == "/mine") {
            this.$router.push({
              path: "/",
            });
          }
          this.$message({
            type: "success",
            message: "退出登录成功!",
          });
        })
        .catch((error) => {
          console.log(error);
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },

    // 搜索查询方法
    async querySearch(_, cb) {
      //  获取查询建议列表
      const res = await this.getSuggestList();
      let articleList = [];
      res.list.forEach((item) => {
        articleList.push({ value: item.content, id: item.id });
      });
      if (articleList.length == 0) {
        setTimeout(() => {
          cb(articleList);
          return this.$showMsg({ msg: "暂无数据!", type: "success" });
        }, 300);
      } else cb(articleList);
    },

    // 获取查询建议列表
    async getSuggestList() {
      const { code, msg, result } = await this.$http.get("/api/tweet/search", {
        params: this.searchQuery,
      });
      console.log(result);
      if (code != 200) {
        return this.$showMsg({ msg: "获取数据失败！", type: "error" });
      }
      return result;
    },

    // 选择查询建议列表
    handleSearchSelect(item) {
      if (this.$route.path == "/comment" && this.$route.query.id == item.id) {
        return;
      }
      // 路由跳转
      this.$router.push({
        path: "/comment",
        query: {
          id: item.id,
        },
      });
      this.querySearch.word = "";
    },
  },
};
</script>

<style lang='less' scoped>
.el-header {
  position: fixed;
  z-index: 1024;
  min-width: 100%;
  box-shadow: 0 2px 3px hsla(0, 0%, 7%, 0.1), 0 0 0 1px hsla(0, 0%, 7%, 0.1);
}
.top-contain-wraper {
  height: 60px;
  align-items: center;
  background-color: #fff;
  .el-col {
    height: 100%;
  }
  .top-contain-left {
    height: 100%;
    display: flex;
    align-items: center;
    text-align: center;
    .top-contain-icon {
      width: 40px;
      height: 40px;
      margin-right: 5px;
      margin-left: 15px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .search {
      // .el-autocomplete {
      //   height: 25px;
      //   padding: 5px;
      //   width: 80%;
      //   display: flex;
      //   border-radius: 10px;
      //   background-color: #f0f1f4;
      //   align-items: center;
      //   color: #aaaaaa;
      //   font-size: 14px;
      // }
    }
  }
  .top-contain-center {
    margin: 0 5px;
    .el-menu {
      width: 100%;
      .el-menu-item {
        width: 25%;
      }
    }
    .iconfont {
      font-size: 30px;
    }
    .pic {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
    .active {
      color: #ff8200;
      border-bottom: 1px solid #ff8200;
    }
  }
  .top-contain-right {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .member-login-register {
      display: flex;
      justify-content: space-between;
      .member-login {
        background-color: #ff8200;
        color: white;
        width: 80px;
        height: 40px;
        line-height: 40px;
        border-radius: 20px;
        text-align: center;
        margin-right: 15px;
        cursor: pointer;
      }
      .member-register {
        height: 40px;
        line-height: 40px;
        cursor: pointer;
      }
    }

    .logout-wrap {
      cursor: pointer;
      font-size: 24px;
      color: #333;
    }
    .write-wrap {
      .write {
        width: 60px;
        height: 40px;
        line-height: 40px;
        border-radius: 10px;
        background-color: #ff8200;
        text-align: center;
        cursor: pointer;
        .el-icon-edit {
          font-size: 18px;
          color: white;
        }
      }
    }
  }
}
</style>>